package com.sunyur.tailor.channel.common.middle.util;

import com.sunyur.tailor.channel.common.middle.base.ChannelResult;
import com.sunyur.tailor.channel.common.middle.enums.MiddleResultEnum;

import java.util.Collection;
import java.util.Map;

/**
 *
 * @Description:返回工具类
 */
public class ChannelResultUtil {

    private ChannelResultUtil() {
    }

    /** *
     * @Description: 获取内容
     */
    public static final <T> T getContent(ChannelResult<T> channelResult){
        if(channelResult != null){
            return channelResult.getContent();
        }
        return null;
    }

    /** *
     * @Description: 生成成功实体对象
     */
    public static final <T> ChannelResult<T> success(T model){
        ChannelResult<T> result = new ChannelResult<>();
        result.setCode(MiddleResultEnum.SUCCESS.getCode());
        result.setContent(model);
        return result;
    }

    /** *
     * @Description: 生成错误实体对象
     */
    public static final <T> ChannelResult<T> error(String code, String message){
        ChannelResult<T> result = new ChannelResult<>();
        result.setCode(code);
        result.setMessage(message);
        return result;
    }

    /**
     * @Description: 判断是否成功
     */
    public static <T> boolean isSuccess(ChannelResult<T> channelResult) {
        if (channelResult != null && channelResult.getCode().equals(MiddleResultEnum.SUCCESS.getCode()) && channelResult.getContent() != null) {
            if (channelResult.getContent() instanceof Boolean) {
                return (Boolean) channelResult.getContent();
            } else if (channelResult.getContent() instanceof Collection<?>) {
                return !((Collection<?>) channelResult.getContent()).isEmpty();
            } else if (channelResult.getContent() instanceof Map<?, ?>) {
                return !((Map<?, ?>) channelResult.getContent()).isEmpty();
            } else if (channelResult.getContent() instanceof Object[]) {
                return ((Object[]) channelResult.getContent()).length != 0;
            }
            return true;
        }
        return false;
    }
}
